package util.thread.threadsafety;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 李栋
 * @version 1.0.0
 * @className ThreadSafetyTest.java
 * @createTime 2021年08月08日 16:25:00
 */
public class ThreadSafetyTest {

    private static final Logger logger = LoggerFactory.getLogger(ThreadSafetyTest.class);

    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 保证线程安全
     */
    private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    /**
     * SimpleDateFormat 类并不是线程安全的
     */
    @Test
    public void test() {
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                try {
                    String dateString = simpleDateFormat.format(new Date());
                    Date parse = simpleDateFormat.parse(dateString);
                    logger.info(simpleDateFormat.format(parse));
                } catch (Exception e) {
                    logger.error("Error Occur:{}", e.getMessage(), e);
                }
            }).start();
        }
    }

    @Test
    public void testOne() {
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                try {
                    String dateString = simpleDateFormat.format(new Date());
                    Date parse = df.get().parse(dateString);
                    logger.info(simpleDateFormat.format(parse));
                } catch (Exception e) {
                    logger.error("Error Occur:{}", e.getMessage(), e);
                }
            }).start();
        }
    }
}
